<template>
  <div class="cart-container">
    <el-card>
      <template #header>
        <div class="cart-header">
          <h2>我的购物车</h2>
          <el-button type="danger" @click="clearCart" :disabled="cartItems.length === 0">
            <el-icon><Delete /></el-icon> 清空购物车
          </el-button>
        </div>
      </template>
      
      <!-- 购物车列表 -->
      <div v-if="cartItems.length > 0">
        <el-table :data="cartItems" style="width: 100%">
          <el-table-column label="药品信息" min-width="300">
            <template #default="scope">
              <div class="cart-item-info">
                <el-image 
                  :src="scope.row.image || 'https://via.placeholder.com/80x80?text=药品图片'" 
                  fit="cover"
                  :alt="scope.row.name"
                  style="width: 80px; height: 80px; margin-right: 15px;"
                ></el-image>
                <div>
                  <div class="cart-item-name">{{ scope.row.name }}</div>
                  <div class="cart-item-price">¥{{ scope.row.price }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="数量" width="200">
            <template #default="scope">
              <el-input-number 
                v-model="scope.row.quantity" 
                :min="1" 
                :max="99" 
                @change="updateCart"
              />
            </template>
          </el-table-column>
          
          <el-table-column label="小计" width="150">
            <template #default="scope">
              <span class="cart-item-subtotal">¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}</span>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button type="danger" @click="removeItem(scope.$index)" size="small">
                <el-icon><Delete /></el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 购物车底部 -->
        <div class="cart-footer">
          <div class="cart-total">
            <span>共 {{ totalItems }} 件商品，合计：</span>
            <span class="cart-total-price">¥{{ totalPrice.toFixed(2) }}</span>
          </div>
          <el-button type="primary" size="large" @click="checkout">
            <el-icon><ShoppingCartFull /></el-icon> 去结算
          </el-button>
        </div>
      </div>
      
      <!-- 空购物车提示 -->
      <el-empty v-else description="购物车还是空的，快去选购药品吧！">
        <el-button type="primary" @click="goToMedicineList">去选购</el-button>
      </el-empty>
    </el-card>
    
    <!-- 结算对话框 -->
    <el-dialog v-model="checkoutDialogVisible" title="订单确认" width="500px">
      <el-form :model="orderForm" label-width="100px">
        <el-form-item label="收货人">
          <el-input v-model="orderForm.receiver" placeholder="请输入收货人姓名" />
        </el-form-item>
        
        <el-form-item label="联系电话">
          <el-input v-model="orderForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
        
        <el-form-item label="收货地址">
          <el-input v-model="orderForm.address" type="textarea" placeholder="请输入详细地址" />
        </el-form-item>
        
        <el-form-item label="支付方式">
          <el-radio-group v-model="orderForm.payType">
            <el-radio :label="0">支付宝</el-radio>
            <el-radio :label="1">微信</el-radio>
            <el-radio :label="2">银行卡</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="期望送达时间">
          <el-date-picker
            v-model="orderForm.deliveryTime"
            type="datetime"
            placeholder="选择期望送达时间"
            :disabled-date="disabledDate"
            :disabled-hours="disabledHours"
          />
        </el-form-item>
        
        <el-form-item label="订单备注">
          <el-input v-model="orderForm.remark" type="textarea" placeholder="请输入订单备注（选填）" />
        </el-form-item>
      </el-form>
      
      <div class="checkout-total">
        <span>订单总计：</span>
        <span class="checkout-price">¥{{ totalPrice.toFixed(2) }}</span>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="checkoutDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitOrder" :loading="submitting">
            提交订单
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, ShoppingCartFull } from '@element-plus/icons-vue'
import { addOrder } from '@/api/order'

const router = useRouter()

// 购物车商品
const cartItems = ref([])

// 结算对话框可见性
const checkoutDialogVisible = ref(false)

// 提交订单状态
const submitting = ref(false)

// 订单表单
const orderForm = ref({
  receiver: '',
  phone: '',
  address: '',
  payType: 0,
  deliveryTime: '',
  remark: ''
})

// 计算总商品数量
const totalItems = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.quantity, 0)
})

// 计算总价
const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.price * item.quantity, 0)
})

// 获取购物车数据
onMounted(() => {
  loadCartItems()
  
  // 获取用户信息填充订单表单
  const userInfoStr = localStorage.getItem('userInfo')
  if (userInfoStr) {
    try {
      const userInfo = JSON.parse(userInfoStr)
      orderForm.value.receiver = userInfo.username || ''
      orderForm.value.phone = userInfo.phoneNumber || ''
      orderForm.value.address = userInfo.address || ''
    } catch (error) {
      console.error('解析用户信息失败', error)
    }
  }
})

// 加载购物车数据
const loadCartItems = () => {
  const cart = localStorage.getItem('cart')
  if (cart) {
    try {
      cartItems.value = JSON.parse(cart)
    } catch (error) {
      console.error('解析购物车数据失败', error)
      cartItems.value = []
    }
  } else {
    cartItems.value = []
  }
}

// 更新购物车
const updateCart = () => {
  localStorage.setItem('cart', JSON.stringify(cartItems.value))
}

// 移除购物车商品
const removeItem = (index) => {
  cartItems.value.splice(index, 1)
  updateCart()
  ElMessage.success('已从购物车移除')
}

// 清空购物车
const clearCart = () => {
  ElMessageBox.confirm('确定要清空购物车吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    cartItems.value = []
    localStorage.removeItem('cart')
    ElMessage.success('购物车已清空')
  }).catch(() => {
    // 取消清空
  })
}

// 前往药品列表
const goToMedicineList = () => {
  router.push('/user/medicine')
}

// 结算
const checkout = () => {
  if (cartItems.value.length === 0) {
    ElMessage.warning('购物车为空，请先添加商品')
    return
  }
  
  checkoutDialogVisible.value = true
}

// 禁用的日期（今天之前的日期）
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7 // 禁用今天之前的日期
}

// 禁用的小时（凌晨0点到早上8点）
const disabledHours = () => {
  return Array.from(Array(8).keys()) // 返回 [0, 1, 2, 3, 4, 5, 6, 7]
}

// 提交订单
const submitOrder = async () => {
  // 表单验证
  if (!orderForm.value.receiver) {
    ElMessage.warning('请输入收货人姓名')
    return
  }
  if (!orderForm.value.phone) {
    ElMessage.warning('请输入联系电话')
    return
  }
  if (!orderForm.value.address) {
    ElMessage.warning('请输入收货地址')
    return
  }
  if (!orderForm.value.deliveryTime) {
    ElMessage.warning('请选择期望送达时间')
    return
  }
  
  submitting.value = true
  
  try {
    // 构建订单数据
    const orderData = {
      ...orderForm.value,
      totalAmount: totalPrice.value * 100, // 转换为分
      items: cartItems.value.map(item => ({
        medicineId: item.id,
        quantity: item.quantity,
        price: item.price
      }))
    }
    
    // 调用创建订单API
    const res = await addOrder(orderData)
    
    if (res && res.id) {
      ElMessage.success('订单提交成功')
      // 清空购物车
      cartItems.value = []
      localStorage.removeItem('cart')
      // 关闭对话框
      checkoutDialogVisible.value = false
      // 跳转到订单详情页
      router.push(`/user/order/detail/${res.id}`)
    } else {
      ElMessage.error('订单提交失败，请稍后再试')
    }
  } catch (error) {
    console.error('提交订单失败', error)
    ElMessage.error('订单提交失败，请稍后再试')
    
    // 模拟订单提交成功
    setTimeout(() => {
      ElMessage.success('订单提交成功')
      // 清空购物车
      cartItems.value = []
      localStorage.removeItem('cart')
      // 关闭对话框
      checkoutDialogVisible.value = false
      // 跳转到订单列表页
      router.push('/user/order')
    }, 1000)
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.cart-container {
  padding: 20px 0;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cart-header h2 {
  margin: 0;
}

.cart-item-info {
  display: flex;
  align-items: center;
}

.cart-item-name {
  font-size: 16px;
  margin-bottom: 5px;
}

.cart-item-price {
  color: #f56c6c;
  font-size: 14px;
}

.cart-item-subtotal {
  color: #f56c6c;
  font-size: 16px;
  font-weight: bold;
}

.cart-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.cart-total {
  margin-right: 20px;
  font-size: 16px;
}

.cart-total-price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
}

.checkout-total {
  text-align: right;
  margin-top: 20px;
  font-size: 16px;
}

.checkout-price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
}
</style>